package com.kyg.tjtoolmanager.controller;

import com.alibaba.fastjson.JSONArray;
import com.kyg.tjtoolmanager.App;
import com.kyg.tjtoolmanager.db.SQLiteUtils;
import com.kyg.tjtoolmanager.module.WareHouse;
import com.kyg.tjtoolmanager.net.http.HttpBack;
import com.kyg.tjtoolmanager.net.http.HttpEntity;
import com.kyg.tjtoolmanager.net.http.HttpService;
import com.kyg.tjtoolmanager.net.http.HttpURL;
import com.kyg.tjtoolmanager.net.netty.factory.ChannelFactory;
import com.kyg.tjtoolmanager.net.netty.hander.FaceLoginListener;
import com.kyg.tjtoolmanager.net.netty.hander.LapiServerFactory;
import com.kyg.tjtoolmanager.ui.ProgressStage;
import com.kyg.tjtoolmanager.ui.StageUIHelper;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import okhttp3.Call;

import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

public class HouseController extends BaseController {

    @FXML
    private GridPane gridPane;
    private boolean isBorrow = false;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        super.initialize(url, resourceBundle);
        SQLiteUtils.insertLog("进入库房管理页面");
    }

    private void bindGridHouse(List<WareHouse> wareHouses) {
//        wareHouses.addAll(wareHouses);
//        wareHouses.addAll(wareHouses);
        int cols = 6, colCnt = 0, rowCnt = 0;
        for (int i = 0; i < wareHouses.size(); i++) {
            WareHouse wareHouse = wareHouses.get(i);
            Button button = new Button(wareHouse.toDoorString());
            button.setPrefHeight(150);
            button.setPrefWidth(150);
            button.setOnMouseClicked(new EventHandler<javafx.scene.input.MouseEvent>() {
                @Override
                public void handle(javafx.scene.input.MouseEvent mouseEvent) {
                    if (mouseEvent.getClickCount() == 1) {
                        SQLiteUtils.insertLog("" + wareHouse.toDoorString());
                    }
                }
            });
            gridPane.add(button, colCnt, rowCnt);
            colCnt++;
            if (colCnt >= cols) {
                rowCnt++;
                colCnt = 0;
            }
        }
    }

    @FXML
    protected void onBorrowClick() {
        if (App.DEBUG) {
            StageUIHelper.toCustomUI("物品领用", "borrow-view.fxml", 0.8f, false);
            return;
        }
        isBorrow = true;
        faceLogin();
    }

    @FXML
    protected void onReturnClick() {
        isBorrow = false;
        faceLogin();
    }

    private void faceLogin() {
        if (!ChannelFactory.isExistIp(App.globalVal.faceIp)) {
            StageUIHelper.getInstance().showTipAlert("人脸识别设备未在线，请确认是否配置正确");
            return;
        }
        LapiServerFactory.addFaceLoginListener(new FaceLoginListener() {
            @Override
            public void onFaceLogin(String personJSON) {
                LapiServerFactory.removeFaceLoginListener(this);
//                SQLiteUtils.insertLog("人脸登陆：" + personJSON);
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        FaceLoginDialog.closeMedia();
                        StageUIHelper.StageMap.get("login-dialog.fxml").close(); //关闭人脸识别窗
                        StageUIHelper.toCustomUI(isBorrow ? "物品领用" : "物品归还", isBorrow ? "borrow-view.fxml" : "return-view.fxml", 0.8f, false);
                    }
                });
            }
        });
        StageUIHelper.getInstance()
                .setTitle("人脸登陆")
                .setFxml("login-dialog.fxml")
                .setPercent(0.3f)
                .setEquWidth(true)
                .setWindowsClosedHandler(new EventHandler<WindowEvent>() {
                    @Override
                    public void handle(WindowEvent windowEvent) {
                        FaceLoginDialog.closeMedia();
                    }
                }).show();
    }

    @Override
    public void onShow() {
        //获取仓库信息
        ProgressStage progressStage = ProgressStage.of((Stage) rootLayout.getScene().getWindow(), "正在获取库房信息");
        progressStage.show();

        Map<String, String> postParams = new HashMap<>();
        postParams.put("warehouse_id", "0");
        HttpService.getInstance().httpGet(HttpURL.URL(HttpURL.GET_HOUSE_INFO), postParams, new HttpBack() {
            @Override
            public void onSuccess(Call call, HttpEntity httpEntity) {
                progressStage.close();
                SQLiteUtils.insertLog("库房接口返回：" + httpEntity.toString());
                try {
                    if (httpEntity.getCode() == 1) {
                        List<WareHouse> wareHouses = JSONArray.parseArray(httpEntity.getData().toString(), WareHouse.class);
                        bindGridHouse(wareHouses);
                    } else {
                        StageUIHelper.getInstance().showTipAlert(httpEntity.getMsg());
                    }
                } catch (Exception ex) {
                    SQLiteUtils.insertLog("库房接口解析错误：" + ex.getMessage());
                }
            }

            @Override
            public void onFail(Call call, String e) {
                progressStage.close();
                SQLiteUtils.insertLog("库房接口错误：" + e);
                StageUIHelper.getInstance().showTipAlert(e);
            }
        });
    }

    @Override
    public void onClose() {
        super.onClose();
    }
}
